import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'index.dart';

class MessageChatPage extends GetView<MessageChatController> {
  const MessageChatPage({super.key});

  // 主视图
  Widget _buildView() {
    return Column(
      children: [
        // 消息列表
        Expanded(
          child: _buildMessageList(),
        ),
        // 输入框
        _buildInputArea(),
      ],
    );
  }

  // 构建消息列表
  Widget _buildMessageList() {
    return Obx(() {
      if (controller.messageList.isEmpty) {
        return Center(
          child: Text(
            '暂无消息，开始聊天吧',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[500],
            ),
          ),
        );
      }

      return ListView.builder(
        controller: controller.scrollController,
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
        itemCount: controller.messageList.length,
        itemBuilder: (context, index) {
          final message = controller.messageList[index];
          return _buildMessageBubble(message);
        },
      );
    });
  }

  // 构建消息气泡
  Widget _buildMessageBubble(ChatMessage message) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            message.isSelf ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!message.isSelf) ...[
            // 对方头像
            ClipOval(
              child: Image.network(
                controller.userAvatar,
                width: 36.w,
                height: 36.h,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: 36.w,
                    height: 36.h,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.grey[300],
                    ),
                    child: Icon(
                      Icons.person,
                      color: Colors.grey,
                      size: 20.r,
                    ),
                  );
                },
              ),
            ),
            SizedBox(width: 8.w),
          ],
          // 消息内容
          Flexible(
            child: Column(
              crossAxisAlignment: message.isSelf
                  ? CrossAxisAlignment.end
                  : CrossAxisAlignment.start,
              children: [
                // 时间
                Text(
                  _formatTime(message.time),
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: Colors.grey[500],
                  ),
                ),
                SizedBox(height: 4.h),
                // 消息气泡
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color: message.isSelf
                        ? const Color(0xFF1890FF)
                        : Colors.white,
                    borderRadius: BorderRadius.circular(8.r),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 4.r,
                        offset: Offset(0, 2.h),
                      ),
                    ],
                  ),
                  child: Text(
                    message.content,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: message.isSelf ? Colors.white : const Color(0xFF1D1D1F),
                    ),
                  ),
                ),
              ],
            ),
          ),
          if (message.isSelf) ...[
            SizedBox(width: 8.w),
            // 自己的头像（使用用户信息）
            ClipOval(
              child: controller.userAvatarUrl.isNotEmpty
                  ? Image.network(
                      controller.userAvatarUrl,
                      width: 36.w,
                      height: 36.h,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 36.w,
                          height: 36.h,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.blue[100],
                          ),
                          child: Icon(
                            Icons.person,
                            color: Colors.blue[700],
                            size: 20.r,
                          ),
                        );
                      },
                    )
                  : Container(
                      width: 36.w,
                      height: 36.h,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.blue[100],
                      ),
                      child: Icon(
                        Icons.person,
                        color: Colors.blue[700],
                        size: 20.r,
                      ),
                    ),
            ),
          ],
        ],
      ),
    );
  }

  // 构建输入区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4.r,
            offset: Offset(0, -2.h),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: Row(
          children: [
            // 更多按钮
            IconButton(
              onPressed: () {},
              icon: Icon(
                Icons.add_circle_outline,
                size: 24.r,
                color: Colors.grey[600],
              ),
            ),
            // 输入框
            Expanded(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                decoration: BoxDecoration(
                  color: const Color(0xFFF5F5F5),
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: TextField(
                  controller: controller.textController,
                  decoration: InputDecoration(
                    hintText: '说点什么...',
                    hintStyle: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[500],
                    ),
                    border: InputBorder.none,
                    isDense: true,
                    contentPadding: EdgeInsets.zero,
                  ),
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF1D1D1F),
                  ),
                  maxLines: 4,
                  minLines: 1,
                ),
              ),
            ),
            SizedBox(width: 8.w),
            // 发送按钮
            GestureDetector(
              onTap: controller.sendMessage,
              child: Container(
                padding: EdgeInsets.all(8.r),
                decoration: const BoxDecoration(
                  color: Color(0xFF1890FF),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.send,
                  size: 20.r,
                  color: Colors.white,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final messageDate = DateTime(time.year, time.month, time.day);

    final hour = time.hour.toString().padLeft(2, '0');
    final minute = time.minute.toString().padLeft(2, '0');
    final timeStr = '$hour:$minute';

    if (messageDate == today) {
      return timeStr;
    } else if (messageDate == today.subtract(const Duration(days: 1))) {
      return '昨天 $timeStr';
    } else {
      final month = time.month.toString().padLeft(2, '0');
      final day = time.day.toString().padLeft(2, '0');
      return '$month-$day $timeStr';
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MessageChatController>(
      init: MessageChatController(),
      id: "message_chat",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF5F5F5),
          appBar: _buildAppBar(),
          body: _buildView(),
        );
      },
    );
  }

  // 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
          size: 20.r,
          color: const Color(0xFF1D1D1F),
        ),
        onPressed: () => Get.back(),
      ),
      title: Text(
        controller.userName,
        style: TextStyle(
          fontSize: 16.sp,
          fontWeight: FontWeight.w600,
          color: const Color(0xFF1D1D1F),
        ),
      ),
      centerTitle: true,
      actions: [
        IconButton(
          icon: Icon(
            Icons.more_horiz,
            size: 24.r,
            color: const Color(0xFF1D1D1F),
          ),
          onPressed: () {},
        ),
      ],
    );
  }
}

